<?php


namespace app\api\service;


use app\api\exception\ThrowException;
use think\facade\Cache;

class Token
{
    /**
     *  验证 Token
     */
    public function check($token)
    {
        return Cache::get($token);
    }


    /**
     *  生成Token码
     */
    public function generateToken()
    {
        $randChar = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = config('api.token_salt');
        return sha1($randChar . $timestamp . $tokenSalt);
    }

    /**
     *  获取 授权Token
     */
    public function get($user)
    {

        $values = [
            'id' => $user->id,
            'cusname' => $user->cusname,
            'isadmin' => $user->isadmin,
            'phone' => $user->phone,
            'email' => $user->email,
            'role' => $user->role
        ];

        return $this->saveToCache($values);
    }

    private function saveToCache($values){

        $token = $this->generateToken();

        $expire_in = config('api.token_expire_in');

        $result = Cache::set($token, json_encode($values), $expire_in);

        if( !$result ){
            throw new ThrowException([
                'message' => 'service.cacheException',
                'errorCode' => 1
            ]);
        }

        return $token;

    }
}
